<script setup>
import {ref,watch,onMounted} from 'vue'
import{queryPageApi,addApi,queryInfoApi,updateApi,violationApi,deleteApi} from '@/api/stu' 
import { queryAllApi } from '../../api/clazz';
import { ElDatePicker, ElMessage,ElMessageBox } from 'element-plus'


// 元数据
// 学历列表数据
const degrees = ref([{name:'初中',value: 1},{name:'高中',value: 2},{name:'大专',value: 3},{name:'本科',value: 4},{name:'硕士',value: 5},{name:'博士',value: 6}])
// 性别列表数据
const genders = ref([{name:'男',value: 1},{name:'女',value: 2}])
// 是否院校学员列表
const isColleges = ref([{name:'是',value: 1},{name:'否',value: 0}])
// 班级列表查询
const clazzList = ref([])
// 查询所有班级
const getClazzList = async () => {
  const result = await queryAllApi()
  if(result.code){ 
    clazzList.value = result.data
  }
}


// 搜索表单对象
const searchStu = ref( {name: '',degree: '',clazzId: ''})

// 学员列表数据
const stuList = ref([])

//查询学员列表
const search = async () => {
  const result = await queryPageApi(searchStu.value.name,searchStu.value.degree,searchStu.value.clazzId,
  currentPage.value,pageSize.value)
  if(result.code){
    stuList.value = result.data.rows
    total.value = result.data.total
  }
}

// 清空按钮
const clear = () => {
  searchStu.value = {name: '',degree: '',clazzId: ''}
  search()
}

// 钩子函数
onMounted(() => {
  search()
  getClazzList()
})

// 分页
const currentPage = ref(1)//页码
const pageSize = ref(10)//每页展示记录数
const background = ref(true)//背景颜色
const total = ref(0)//总记录数

// 每页展示记录数变化
const handleSizeChange = (val) => {
  search()
}
// 页码变化时触发
const handleCurrentChange = (val) => {
  search()
}


// 新增/修改表单
const stu = ref({
  name: '',
  no: '',
  gender: '',
  phone: '',
  idCard: '',
  isCollege: '',
  address: '',
  degree: '',
  graduationDate: '',
  clazzId: '',
  violationCount: '',
  violationScore: '',
  createTime: '',
  updateTime: ''
})

// Dialog对话框
const dialogVisible = ref(false)
const dialogTitle = ref('添加学员')

// 添加学员按钮
const addStu = () => {
  dialogVisible.value = true
  dialogTitle.value = '添加学员'
  stu.value = {name: '',no: '',gender: '',phone: '',idCard: '',isCollege: '',address: '',degree: '',graduationDate: '',clazzId: ''}
     // 重置表单的校验规则-提示信息
  if(stuFormRef.value){
    stuFormRef.value.resetFields()
  }
}

const stuFormRef = ref();
// 表单校验
const rules = ref({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
  ],
  no: [
    { required: true, message: '请输入学号', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
  ],
  degree: [
    { required: true, message: '请选择学历', trigger: 'blur' }
  ],
  clazzId: [
    { required: true, message: '请选择班级', trigger: 'blur' }
  ],
  isCollege: [
    { required: true, message: '请选择是否院校学员', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的身份证号' },
    { min: 18, max: 18, message: '请输入18位身份证号' }
  ],
  violationScore: [
    { required: true, message: '请输入学员违规分值', trigger: 'blur' },
    { 
      type: 'number', 
      message: '请输入数字', 
      trigger: 'blur',
      transform: (value) => Number(value)  // 字符串转数字
    }
]

})

// 保存按钮（添加/修改学员）
const save = async () => {
  if(!stuFormRef.value){
    return
  }
  stuFormRef.value.validate(async (valid) => {
    if(valid){//通过 校验通过
      let result
      if(stu.value.id){//修改
        result = await updateApi(stu.value)
      }else{//新增
        result = await addApi(stu.value)
      }

      if(result.code){ //成功
        //1. 提示消息
        ElMessage.success('保存成功')
        //2. 关闭对话框
        dialogVisible.value = false
        //3. 查询
        search()
      }
      else{//失败
        ElMessage.error(result.msg)
      }
    }else{//不通过
      ElMessage.error('表单校验不通过')
    }
  })
}

// 编辑学员按钮
const edit = async (id) => {
  const result = await queryInfoApi(id)
  if(result.code){ 
    stu.value = result.data
    dialogVisible.value = true
    dialogTitle.value = '编辑学员'
  }else{
    ElMessage.error(result.msg)
  }  
}

// 违纪Dialog对话框
const violationDialogVisible = ref(false)

// 违纪按钮 - 弹出对话框
const violation = (id) => {
  violationDialogVisible.value = true
  stu.value.id = id
       // 重置表单的校验规则-提示信息
  if(stuFormRef.value){
    stuFormRef.value.resetFields()
  }
}
// 违纪处理 - 确定按钮
const violationSave = async () => {
  const result = await violationApi(stu.value.id,stu.value.violationScore)
  if(result.code){
    ElMessage.success('处理成功')
    violationDialogVisible.value = false
    search()
  }
  else{
    ElMessage.error(result.msg)
  }
}

// 删除按钮 - 根基ID删除单个学员
const deleteById = (id) => {
  ElMessageBox.confirm('您确定要删除该学员吗 ?','提示',
  {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning',}
  ).then( async () => {//确认
    try {
    const result = await deleteApi(id)
    if(result.code){
      ElMessage.success('删除成功')
      search()
    }
    else{
      ElMessage.error(result.msg)
    }
    }catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {//取消
    ElMessage.info('您已取消删除')
  })
}

// 记录勾选的学员ID
const selectedIds = ref([])
// 复选框勾选发生变化时触发 - selection:当前选中的记录组成的数组
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => {
    return item.id
  })
}
// 批量删除学员
const deleteByIds = async () => {
  ElMessageBox.confirm('您确定要删除该学员吗 ?','提示',
  {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning',}
  ).then( async () => {//确认
    if(selectedIds && selectedIds.value.length > 0 ){
      try {
        const result = await deleteApi(selectedIds.value)
        if(result.code){
          ElMessage.success('删除成功')
          search()
        }
        else{
          ElMessage.error(result.msg)
        }
        }catch (error) {
          ElMessage.error('删除失败')
        }
    }else{
      ElMessage.warning('请选择要删除的学员')
    }
  }).catch(() => {//取消
    ElMessage.info('您已取消删除')
  })
}
</script>

<template>
 <h1>学员管理</h1>
  <!-- 搜索栏 -->
   <div class="container">
    <el-form :inline="true" :model="searchStu" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="searchStu.name" placeholder="请输入学员姓名" clearable />
    </el-form-item>
    <el-form-item label="最高学历">
      <el-select v-model="searchStu.degree" placeholder="请选择" clearable>
        <el-option v-for="degree in degrees" :key="degree.value" :label="degree.name" :value="degree.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="所属班级">
      <el-select v-model="searchStu.clazzId" placeholder="请选择" clearable>
        <el-option v-for="clazz in clazzList" :key="clazz.id" :label="clazz.name" :value="clazz.id" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
  </div>


   <!-- 功能按钮 -->
  <div class="container">
    <el-form-item>
      <el-button type="primary" @click="addStu"> + 添加学员</el-button>
      <el-button type="danger" @click="deleteByIds"> - 批量删除</el-button>
    </el-form-item>
  </div>


  <!-- 学员列表 -->
  <div class="container">
    <el-table :data="stuList" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="45" align="center" />
    <el-table-column prop="name" label="姓名" width="80" align = "center" />
    <el-table-column prop="no" label="学号" width="120" align = "center" />
    <el-table-column prop="clazzName" label="班级" width="150" align = "center" />
    <el-table-column prop="gender" label="性别" width="60" align = "center" >
      <template #default="scope">
        {{ scope.row.gender == 1 ? '男' : '女' }}
      </template>
    </el-table-column>
    <el-table-column prop="phone" label="手机号" width="120" align = "center" />
    <el-table-column prop="degree" label="最高学历" width="90" align = "center" >
       <template #default="scope">
        <span v-if="scope.row.degree === 1">初中</span>
        <span v-else-if="scope.row.degree === 2">高中</span>
        <span v-else-if="scope.row.degree === 3">大专</span>
        <span v-else-if="scope.row.degree === 4">本科</span>
        <span v-else-if="scope.row.degree === 5">硕士</span>
        <span v-else-if="scope.row.degree === 6">博士</span>
        <span v-else>其他</span>
      </template>
    </el-table-column>
    <el-table-column prop="violationCount" label="违纪次数" width="90" align = "center" />
    <el-table-column prop="violationScore" label="违纪扣分" width="90" align = "center" />
    <el-table-column prop="updateTime" label="最后操作时间" width="160" align = "center" />
    <el-table-column prop="operation" label="操作"  align = "center" >
      <template #default="scope"> 
        <el-button size="small" type="primary" @click="edit(scope.row.id)"><el-icon><Edit /></el-icon>编辑</el-button>
        <el-button size="small" type="warning" @click="violation(scope.row.id)"><el-icon><Warning /></el-icon>违纪</el-button>
        <el-button size="small" type="danger" @click="deleteById(scope.row.id)"><el-icon><Delete /></el-icon>删除</el-button>
      </template>
    </el-table-column>
    </el-table>
  </div>

<!-- 分页条 -->
  <div class="container">
    <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :page-sizes="[5,10, 20, 30, 40, 50,75,100]"
    :background="background"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
  </div>

<!-- 新增学员/修改学员Dialog对话框 -->
<el-dialog v-model="dialogVisible" :title="dialogTitle" >
    <el-form :model="stu" label-width="80px" :rules="rules" ref="stuFormRef">
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="stu.name"  placeholder="请输入姓名"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学号" prop="no">
            <el-input v-model="stu.no" placeholder="请输入学号"/>
          </el-form-item>
        </el-col>
      </el-row>

    <!-- 第二行 -->
     <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="stu.gender" style="width: 100%;" placeholder="请选择">
              <el-option v-for="gender in genders" :key="gender.value" :label="gender.name" :value="gender.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="stu.phone" placeholder="请输入手机号" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
        <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="stu.idCard" placeholder="请输入身份证号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否院校学员" prop="isCollege">
            <el-select v-model="stu.isCollege" style="width: 100%;" placeholder="请选择">
              <el-option v-for="isCollege in isColleges" :key="isCollege.value" :label="isCollege.name" :value="isCollege.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系地址" prop="address">
            <el-input v-model="stu.address" placeholder="请输入联系地址" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高学历" prop="degree">
            <el-select v-model="stu.degree" style="width: 100%;" placeholder="请选择" clearable>
              <el-option v-for="degree in degrees" :key="degree.value" :label="degree.name" :value="degree.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="毕业时间" prop="graduationDate">
            <el-date-picker v-model="stu.graduationDate" type="date" style="width: 100%;" placeholder="请选择毕业时间" 
            format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班级" prop="clazzId">
            <el-select v-model="stu.clazzId" style="width: 100%;" placeholder="请选择" clearable>
              <el-option v-for="clazz in clazzList" :key="clazz.id" :label="clazz.name" :value="clazz.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button type="info" @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
</el-dialog>


<!-- 违纪处理Dialog对话框 -->
<el-dialog v-model="violationDialogVisible" title="学员违纪处理" >
    <el-form :model="stu" label-width="80px" :rules="rules" ref="violationFormRef">
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="违纪扣分" prop="violationScore">
            <el-input v-model="stu.violationScore" style="width: 80%;" placeholder="请输入违纪扣分"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 底部按钮 -->
    <template #footer >
      <div class="dialog-footer" >
        <el-button type="primary" @click="violationSave">确定</el-button>
        <el-button type="info" @click="violationDialogVisible = false">取消</el-button>
      </div>
    </template>
</el-dialog>
</template>

<style scoped>
.container{
  margin: 20px 0px;
}


</style>